package sourceagile.server.classRepositories.subversionFileRepository;

import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNLogEntryPath;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.io.SVNRepository;

/** 
 * 
 * 
 * @MainFeature 
 */

public class ListRepositoryHistory {

	public static String TIME = "time";

	public static String TOTAL_FILES = "total_files";

	public static String TOTAL_EFFORT = "total_effort";

	public static JSONArray getHistory(String repositoryURL, String username,
			String password) {

		JSONArray jsonProductivities = new JSONArray();

		try {

			SVNRepository repository = SubversionRepositoryConnection.connect(
					repositoryURL, username, password);

			long startRevision = 0;
			long endRevision = -1; // HEAD (the latest) revision

			Collection logEntries = repository.log(new String[] { "" }, null,
					startRevision, endRevision, true, true);

			for (Iterator entries = logEntries.iterator(); entries.hasNext();) {

				try {

					SVNLogEntry logEntry = (SVNLogEntry) entries.next();

					JSONObject jsonProductivityEntry = new JSONObject();

					jsonProductivityEntry.put(TIME, logEntry.getDate()
							.getTime());

					int totalClasses = 0;
					int totalActivity = 0;

					if (logEntry.getChangedPaths().size() > 0) {

						Set changedPathsSet = logEntry.getChangedPaths()
								.keySet();

						for (Iterator changedPaths = changedPathsSet.iterator(); changedPaths
								.hasNext();) {

							SVNLogEntryPath entryPath = (SVNLogEntryPath) logEntry
									.getChangedPaths().get(changedPaths.next());

							if (entryPath.getKind() == SVNNodeKind.FILE) {

								if (entryPath.getType() == SVNLogEntryPath.TYPE_ADDED) {

									// productivity.setClassesCount(productivity
									// .getClassesCount() + 1);
									totalClasses++;
								}

								if (entryPath.getType() == SVNLogEntryPath.TYPE_DELETED) {

									totalClasses--;
								}

								// productivity.setClassActivityCount(productivity
								// .getClassActivityCount() + 1);
								totalActivity++;
							}
						}
					}

					jsonProductivityEntry.put(TOTAL_FILES, totalClasses);

					jsonProductivityEntry.put(TOTAL_EFFORT, totalActivity);

					jsonProductivities.put(jsonProductivityEntry);

				} catch (JSONException e) {

					e.printStackTrace();
				}
			}

		} catch (SVNException e1) {

			e1.printStackTrace();
		}

		return jsonProductivities;
	}

}
